package com.ptszyxx.popose.module.main.user;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioGroup;

import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProviders;

import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.common.constants.BundleConstant;
import com.ptszyxx.popose.common.utils.YActivityUtil;
import com.ysg.utils.YChannelUtil;
import com.ysg.enums.NoDiamondEnum;
import com.ysg.http.data.entity.user.UserAppEntity;
import com.ptszyxx.popose.common.utils.YVoiceUtil;
import com.ptszyxx.popose.databinding.FragmentUserDetailBinding;
import com.ptszyxx.popose.module.main.user.vm.UserDetailVM;
import com.stx.xhb.xbanner.XBanner;
import com.ysg.base.BaseFragment;
import com.ysg.http.data.AppViewModelFactory;
import com.ysg.http.data.entity.user.UserAuthEntity;
import com.ysg.http.data.entity.user.UserGuardEntity;
import com.ysg.http.data.entity.user.UserResult;
import com.ysg.utils.YCollectionUtil;
import com.ysg.utils.YDialogUtil;
import com.ysg.utils.YImageUtil;
import com.ysg.utils.YStatusBarUtil;
import com.ysg.utils.YStringUtil;
import com.ysg.widget.dialog.ConfirmDialog;
import com.ysg.widget.dialog.GiftDialog;
import com.ysg.widget.dialog.GuardDialog;
import com.ysg.widget.dialog.entity.GiftListResult;
import com.ysg.widget.dialog.entity.GiftNumResult;
import com.ysg.widget.pic.YPicUtils;

import java.util.List;

public class UserDetailFragment extends BaseFragment<FragmentUserDetailBinding, UserDetailVM> {

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_user_detail;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public UserDetailVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(UserDetailVM.class);
    }

    @Override
    public void onPause() {
        super.onPause();
        YVoiceUtil.getInstance().stopPlay();
    }

    @Override
    public void initParam() {
        super.initParam();
        Bundle bundle = getArguments();
        if (bundle != null){
            viewModel.userId = bundle.getString(BundleConstant.USER_ID);
        }
    }

    @Override
    public void initStatusBar() {
        super.initStatusBar();
        YStatusBarUtil.setImageTheme(this, binding.title);
        //吸顶效果
        binding.scrollview.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY > binding.banner.getHeight()) {
                    binding.title.setVisibility(View.GONE);
                    binding.title2.setVisibility(View.VISIBLE);
                    YStatusBarUtil.setColorTheme(UserDetailFragment.this, binding.title2, com.ysg.R.color.titleBgColor);
                } else {
                    binding.title.setVisibility(View.VISIBLE);
                    binding.title2.setVisibility(View.GONE);
                    YStatusBarUtil.setColorTheme(UserDetailFragment.this, binding.title, com.ysg.R.color.transparent);
                    YStatusBarUtil.setImageTheme(UserDetailFragment.this, binding.title);
                }
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.requestUser();
        viewModel.requestGuard();
    }

    @Override
    public void initView() {
        super.initView();
        initTab();
        setNumberUI();
        setMyUI();

        if (YChannelUtil.getInstance().beta()){
            binding.viewTest.setVisibility(View.VISIBLE);
        }
    }

    private void initTab(){
        showFragment(0);
        binding.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                if (checkedId == R.id.rb_my) {
                    showFragment(0);
                }else if (checkedId == R.id.rb_dynamic) {
                    showFragment(1);
                }
            }
        });
    }

    private UserDetailMineFragment mineFragment;
    private UserDetailDynamicFragment dynamicFragment;
    private void showFragment(int currentItem){
        FragmentManager fragmentManager = getChildFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (mineFragment != null){
            transaction.hide(mineFragment);
        }
        if (dynamicFragment != null){
            transaction.hide(dynamicFragment);
        }
        if (0 == currentItem){
            if (mineFragment == null){
                mineFragment = new UserDetailMineFragment(viewModel.userId);
                transaction.add(R.id.fragmentManager, mineFragment);
            }else {
                transaction.show(mineFragment);
            }
        }else{
            if (dynamicFragment == null){
                dynamicFragment = new UserDetailDynamicFragment(viewModel.userId);
                transaction.add(R.id.fragmentManager, dynamicFragment);
            }else {
                transaction.show(dynamicFragment);
            }
        }
        transaction.commit();
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.onBannerEvent.observe(this, o -> setBannerUI((List<String>)o));
        viewModel.uc.onVoiceEvent.observe(this, o -> setVoiceUI());
        viewModel.uc.onUserAuthEvent.observe(this, o -> setUserAuthUI((List<UserAuthEntity>)o));
        viewModel.uc.onFollowEvent.observe(this, o -> setFollowUI());
        viewModel.uc.onOtherEvent.observe(this, o -> setOtherUI());
        viewModel.uc.onUserMineEvent.observe(this, o -> setUserMineUI());
        viewModel.uc.onGuardEvent.observe(this, o -> setGuardUI());
        viewModel.uc.onGuardDialogEvent.observe(this, o -> showDialogGuard());
        viewModel.uc.onVipEvent.observe(this, o -> showDialogVip());
        viewModel.uc.onBuyEvent.observe(this, o -> showDialogBuy());
        viewModel.uc.onBuyedEvent.observe(this, o -> showDialogBuyed());
        viewModel.uc.onLookDiamondEvent.observe(this, o -> showDialogLookDiamond((UserAppEntity)o));

        viewModel.baseUC.onGiftDialogEvent.observe(this, o -> showDialogGift());
        viewModel.baseUC.onNoDiamondGiftEvent.observe(this, o -> showDialogNoDiamond(NoDiamondEnum.gift));
        viewModel.baseUC.onNoDiamondCallEvent.observe(this, o -> showDialogNoDiamond(NoDiamondEnum.call));
        viewModel.baseUC.onIntimacyEvent.observe(this, o -> showDialogIntimacyGift((String) o));
    }

    /**
     * 如果是自己的话：隐藏一些布局
     */
    private void setMyUI() {
        if (viewModel.isSelf()){
            binding.rlGuard.setVisibility(View.GONE);
            binding.tvFollow.setVisibility(View.GONE);
            binding.viewBottom.setVisibility(View.GONE);
        }
    }

    /**
     * 查看手机号，微信号，QQ号
     */
    private void setNumberUI(){
        if (!viewModel.isSelf() && viewModel.userConfig != null &&
                (YStringUtil.eq(2, viewModel.userConfig.getUserSwitch()) || YStringUtil.eq(3, viewModel.userConfig.getUserSwitch()))  )
        {
            binding.viewNumber.setVisibility(View.VISIBLE);
        }else{
            binding.viewNumber.setVisibility(View.GONE);
        }
    }

    /**
     * 轮播图
     */
    private void setBannerUI(List<String> list) {
        if (YCollectionUtil.isNotEmpty(list)){
            binding.banner.setData(list, null);
            // 加载图片
            binding.banner.loadImage(new XBanner.XBannerAdapter() {
                @Override
                public void loadBanner(XBanner banner, Object model, final View view, int position) {
                    YImageUtil.show((ImageView) view, list.get(position));
                }
            });
            binding.banner.setOnItemClickListener(new XBanner.OnItemClickListener() {
                @Override
                public void onItemClick(XBanner banner, Object model, View view, int position) {
                    YPicUtils.getInstance().zoomPic(getContext(), list, position);
                }
            });
            binding.banner.setClipToOutline(true);
        }
    }

    /**
     * 用户认证：手机，实名，真人
     */
    private void setUserAuthUI(List<UserAuthEntity> list) {
        if (YCollectionUtil.isNotEmpty(list)){
            for (UserAuthEntity entity: list) {
                String authNameEn = entity.getAuthNameEn();
                if (YStringUtil.eq("MOBILE_AUTH", authNameEn)){
                    binding.tvShoujirenzheng.setText(entity.getAuthName());
                }else if (YStringUtil.eq("REAL_NAME_AUTH", authNameEn)){
                    if (YStringUtil.eq(2, entity.getStatus())){
                        binding.ivZhenren.setVisibility(View.VISIBLE);
                    }
                }else if (YStringUtil.eq("REAL_AUTH", authNameEn)){
                    if (YStringUtil.eq(2, entity.getStatus())){
                        binding.tvZhenrenrenzheng.setText(entity.getAuthName());
                    }
                }
            }
        }
    }
    /**
     * 关注
     */
    private void setFollowUI() {
        UserResult data = viewModel.userEntity.get();
        if (null == data){
            return;
        }
        if (YStringUtil.eq(1, data.getGuanzhuState())) {
            binding.tvFollow.setText(getResources().getString(R.string.dynamic_follow_select));
            binding.tvFollow.setTextColor(getResources().getColor(com.ysg.R.color.grayColor));
            binding.tvFollow.setBackground(getResources().getDrawable(R.drawable.shape_follow_unselect));
        } else if (YStringUtil.eq(2, data.getGuanzhuState())) {
            binding.tvFollow.setText(getResources().getString(R.string.dynamic_follow_unselect));
            binding.tvFollow.setTextColor(getResources().getColor(com.ysg.R.color.white));
            binding.tvFollow.setBackground(getResources().getDrawable(R.drawable.shape_follow_select));
        }
    }
    /**
     * 语音
     */
    private void setVoiceUI() {
        binding.voiceView.setVisibility(View.VISIBLE);
        binding.voiceView.setData(viewModel.userEntity.get().getSignatureDto().getVoiceUrl(), viewModel.userEntity.get().getSignatureDto().getSeconds()+"");
    }
    /**
     * 个性签名
     */
    private void setOtherUI() {
        UserResult data = viewModel.userEntity.get();
        if (null == data){
            return;
        }
        //个性签名
        if (YStringUtil.isNotEmpty(data.getMysign())){
            binding.tvSignature.setText(data.getMysign());
        }
    }
    /**
     * tab：我的
     */
    private void setUserMineUI() {
        UserResult data = viewModel.userEntity.get();
        if (null == data){
            return;
        }
        if (mineFragment != null){
            mineFragment.setSexUI(data.getSex());
        }
    }
    /**
     * 守护
     * isHaveGuard:1.有 2.无
     */
    private void setGuardUI() {
        UserGuardEntity guardEntity= viewModel.guardEntity.get();
        if (guardEntity != null){
            if (YStringUtil.eq(1, guardEntity.getIsHaveGuard())){
                YImageUtil.show(binding.guardAvatar, guardEntity.getPic());
                binding.ivAdd.setImageResource(R.mipmap.ic_guard_bg);
            }else if (YStringUtil.eq(2, guardEntity.getIsHaveGuard())){
                binding.ivAdd.setImageResource(R.mipmap.ic_guard_add_bg);
            }
        }
    }

    /**
     * 守护
     */
    private void showDialogGuard(){
        UserResult entity = viewModel.userEntity.get();
        UserGuardEntity guardEntity = viewModel.guardEntity.get();
        if (entity != null && guardEntity != null){
            YDialogUtil.getInstance().showGuard(getContext(), entity.getPic(), entity.getNick(), guardEntity.getPayMoney())
                    .setOnConfirmListener(new GuardDialog.OnConfirmListener() {
                        @Override
                        public void onConfirmClick() {
                            viewModel.onGiftClick();
                        }
                    });
        }
    }
    /**
     * 礼物
     */
    private void showDialogGift(){
        UserResult entity = viewModel.userEntity.get();
        if (entity != null){
            YDialogUtil.getInstance().showGift(getContext(), viewModel.giftListEntity, viewModel.giftNumResult)
                    .setOnGiftListener(new GiftDialog.OnGiftListener() {
                        @Override
                        public void onRechargeClick() {
                            YActivityUtil.getInstance().jumpMineRecharge(viewModel);
                        }

                        @Override
                        public void onSendClick(GiftListResult.GiftBean giftBean, GiftNumResult.Data giftNumEntity) {
                            viewModel.requestSendGift(giftBean, giftNumEntity,  viewModel.userEntity.get().getTengxuncode(), null,  (gifUrl)->
                                showDialogSvga(gifUrl)
                            );
                        }
                    });
        }
    }

    /**
     * 礼物SVGA
     */
    private void showDialogSvga(String url){
        YDialogUtil.getInstance().showSVGA(getContext(), url);
    }

    /**
     * vip
     */
    private void showDialogVip() {
        YDialogUtil.getInstance().showVipRecharge(getContext());
    }

    /**
     * 钻石购买
     */
    private void showDialogBuy() {
        String content = String.format(getResources().getString(R.string.dialog_buy_content), viewModel.userConfig.getUserInfoSeePrice());
        YDialogUtil.getInstance().showConfirm(getContext(), content)
                .setOnConfirmListener(new ConfirmDialog.OnConfirmListener() {
                    @Override
                    public void onConfirmClick() {
                        viewModel.requestBuy();
                    }
                });
    }

    /**
     * 钻石购买过了：显示手机号
     */
    private void showDialogBuyed() {
        YDialogUtil.getInstance().showConfirm(getContext(), getResources().getString(R.string.phone)+"："+viewModel.userEntity.get().getPhoneNum());
    }

    /**
     * 亲密度礼物
     */
    private void showDialogIntimacyGift(String intimacyValue) {
        YDialogUtil.getInstance().showIntimacyGift(getContext(), intimacyValue)
                .setOnIntimacyGiftListener(()-> viewModel.onGiftClick());
    }

    /**
     * 没有钻石
     */
    private void showDialogNoDiamond(NoDiamondEnum noDiamondEnum) {
        YDialogUtil.getInstance().showNoDiamond(getContext(), noDiamondEnum, true);
    }
    /**
     * 查看对方金币，钻石
     */
    private void showDialogLookDiamond(UserAppEntity entity) {
        String content = "位置："+ entity.getAddressdetail() + "    经纬度：" + entity.getLat() + "," + entity.getLon()
                + "\n金币：" + entity.getJinbi() + "\n钻石：" + entity.getDiamonds();
        YDialogUtil.getInstance().showConfirm(getContext(), content, "取消", "跳转地图").setOnConfirmListener(new ConfirmDialog.OnConfirmListener() {
            @Override
            public void onConfirmClick() {
                YActivityUtil.getInstance().jumpMapAddress(viewModel, entity.getId(), entity.getPic(), entity.getNick(), entity.getLat(), entity.getLon());
            }
        });
    }

}
